package com.example.hemin.fnb.ui.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioAttributes;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hemin.fnb.R;
import com.example.hemin.fnb.ui.adapter.ClassSAdapter;
import com.example.hemin.fnb.ui.adapter.FindDailydapter;
import com.example.hemin.fnb.ui.adapter.FindHTAdapter;
import com.example.hemin.fnb.ui.adapter.FindHDAdapter;
import com.example.hemin.fnb.ui.adapter.FindRankdapter;
import com.example.hemin.fnb.ui.adapter.FindYLAdapter;
import com.example.hemin.fnb.ui.adapter.FindZaZhiSAdapter;
import com.example.hemin.fnb.ui.base.BaseMvpFragment;
import com.example.hemin.fnb.ui.bean.BaseObjectBean;
import com.example.hemin.fnb.ui.bean.ClassListBean;
import com.example.hemin.fnb.ui.bean.ClassSItem;
import com.example.hemin.fnb.ui.bean.DailyItem;
import com.example.hemin.fnb.ui.bean.Find2Bean;
import com.example.hemin.fnb.ui.bean.Find2Tiem;
import com.example.hemin.fnb.ui.bean.Find4Bean;
import com.example.hemin.fnb.ui.bean.Find5Bean;
import com.example.hemin.fnb.ui.bean.FindBean;
import com.example.hemin.fnb.ui.bean.FindDeilyBean;
import com.example.hemin.fnb.ui.bean.FindHuoListBean;
import com.example.hemin.fnb.ui.bean.HDItem;
import com.example.hemin.fnb.ui.bean.MessageBean1;
import com.example.hemin.fnb.ui.bean.RankItem;
import com.example.hemin.fnb.ui.bean.YlItem;
import com.example.hemin.fnb.ui.bean.ZZSItem;
import com.example.hemin.fnb.ui.contract.FindContract;
import com.example.hemin.fnb.ui.interfaces.OnFindClickListener;
import com.example.hemin.fnb.ui.interfaces.OnRecyclerItemClickListener;
import com.example.hemin.fnb.ui.net.APIService;
import com.example.hemin.fnb.ui.net.RetrofitClient;
import com.example.hemin.fnb.ui.net.RetrofitClientS;
import com.example.hemin.fnb.ui.net.TextApi;
import com.example.hemin.fnb.ui.presenter.FindPresenter;
import com.example.hemin.fnb.ui.util.AppUtils;
import com.example.hemin.fnb.ui.util.ProgressDialog;
import com.example.hemin.fnb.ui.util.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.Subject;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

public class TabFindFragment extends BaseMvpFragment<FindPresenter> implements FindContract.View {
    @BindView(R.id.find_recyclerview)
    RecyclerView findRecyclerview;
    Unbinder unbinder;
    @BindView(R.id.c1)
    ConstraintLayout c1;
    Unbinder unbinder1;
    @BindView(R.id.find_logo)
    ImageView findLogo;
    private int sendPost = 0;
    private Map Authorization = new HashMap();
    private String userId;
    private MultiTypeAdapter adapter;
    private Items items;
    private List<MessageBean1.DataBean.RecordsBean> zzList = null;
    private List<ClassListBean.DataBean.RecordsBean> classList = null;
    private List<Find2Bean.DataBean.RecordsBean> find2List = null;
    private FindDeilyBean.DataBean find3List = null;
    private List<Find4Bean> find4List = null;
    private Find5Bean.DataBean.RecordsBean find5List = null;
    private FindDailydapter findDailydapter = new FindDailydapter();
    private FindZaZhiSAdapter zzAdapter = new FindZaZhiSAdapter();
    private TextView textView1, textView2, textView3;
    private int ZPageSize = 1;


    @Override
    protected void initView(View view) {
        mPresenter = new FindPresenter();
        mPresenter.attachView(this);
        initDate();
    }

    @Override
    public void lazyInitView(View view) {

    }

    private void initDate() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        SharedPreferences sp = getActivity().getSharedPreferences("userDate", Context.MODE_PRIVATE);
        Authorization = Utils.getAuthorization(getActivity());
        userId = sp.getString("userId", "");
        initRecyclerView();
        intViewNetWork();

    }

    @Subscribe(id = 12)
    public void onLoad(final SmartRefreshLayout smartRefreshLayout) {
        ZPageSize++;
        Observable zz = RetrofitClient.getInstance().getApi().getMaga(Authorization, ZPageSize, 10, "1");
        zz.subscribeOn(Schedulers.io()).subscribeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                BaseObjectBean baseObjectBean = (BaseObjectBean) o;
                if (baseObjectBean.getData() instanceof MessageBean1.DataBean) {
                    addItem(baseObjectBean.getData(), 6);
                    smartRefreshLayout.finishLoadMore(100);


                }
            }
        });
    }

    private void intViewNetWork() {
        Observable huo = RetrofitClient.getInstance().getApi().pageListHuo(Authorization, 1, 3);
        Observable hua = RetrofitClient.getInstance().getApi().addHua(Authorization, 1, 1);
//      Observable daily = RetrofitClient.getInstance().getApi().getDaily(Authorization, Long.parseLong(userId));
//      Observable love = RetrofitClient.getInstance().getApi().guessLove(Authorization);
//      Observable rk = RetrofitClient.getInstance().getApi().getRankingLists(Authorization,1,10);
        Observable zz = RetrofitClient.getInstance().getApi().getMaga(Authorization, 1, 10, "1");
        Observable cm = RetrofitClient.getInstance().getApi().getListClass(Authorization, 1, 10);
        Observable.concatArray(huo, hua, zz, cm).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Subject() {
                    @Override
                    public boolean hasObservers() {
                        return false;
                    }

                    @Override
                    public boolean hasThrowable() {
                        return false;
                    }

                    @Override
                    public boolean hasComplete() {
                        return false;
                    }

                    @Override
                    public Throwable getThrowable() {
                        return null;
                    }

                    @Override
                    protected void subscribeActual(Observer observer) {

                    }

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Object o) {
                        BaseObjectBean baseObjectBean = (BaseObjectBean) o;
                        if (baseObjectBean.getData() instanceof FindHuoListBean.DataBean) {
                            addItem(baseObjectBean.getData(), 1);
                        } else if (baseObjectBean.getData() instanceof Find2Bean.DataBean) {
                            addItem(baseObjectBean.getData(), 2);
                        } else if (baseObjectBean.getData() instanceof ClassListBean.DataBean) {
                            addItem(baseObjectBean.getData(), 7);
                        } else if (baseObjectBean.getData() instanceof FindDeilyBean.DataBean) {
                            addItem(baseObjectBean.getData(), 3);
                        } else if (baseObjectBean.getData() instanceof Find4Bean.DataBean) {
                            addItem(baseObjectBean.getData(), 4);
                        } else if (baseObjectBean.getData() instanceof Find5Bean.DataBean) {
                            addItem(baseObjectBean.getData(), 5);
                        } else if (baseObjectBean.getData() instanceof MessageBean1.DataBean) {
                            addItem(baseObjectBean.getData(), 6);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("awdawdawd", e.toString());
                    }

                    @Override
                    public void onComplete() {
                    }
                });


    }

    @Override
    protected int getLayoutId() {
        return R.layout.find_view;
    }


    @Override
    public void onSuccess(BaseObjectBean bean) {
        if (bean.getErrorCode() != 0) {
            Toast.makeText(getActivity(), bean.getErrorMsg(), Toast.LENGTH_SHORT).show();
        } else {
            sendPost++;
        }

    }


    @Override
    public void showLoading() {
        ProgressDialog.getInstance().show(getContext());
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }


    @Override
    public void Date(Object bean, int status, TextView textView) {
        if (status == 7) {
            textView.setText("1");
        } else if (status == 8) {
            textView.setText("2");
        } else if (status == 9) {
            textView.setText("3");
        }
//        if (status == 7){
//            textView1.setText("dfsefsef");
//        }else if(status == 8){
//            textView2.setText("waerahns");
//        }else if(status == 9){
//            textView3.setText("wshngcfxdf");
//        }


    }

    private void addItem(Object object, int status) {
        if (status == 1) {
            FindHuoListBean.DataBean findBeanList = (FindHuoListBean.DataBean) object;
            List<FindHuoListBean.DataBean.RecordsBean> zz = findBeanList.getRecords();
            for (int m = 0; m < zz.size(); m++) {
                HDItem item1 = new HDItem(zz.get(m));
                items.add(item1);
            }
        } else if (status == 2) {
            Find2Bean.DataBean find2Bean = (Find2Bean.DataBean) object;
            List<Find2Bean.DataBean.RecordsBean> z2 = find2Bean.getRecords();
            for (int i = 0; i < z2.size(); i++) {
                Find2Tiem item2 = new Find2Tiem(z2.get(i));
                items.add(item2);
            }
        } else if (status == 3) {
            find3List = (FindDeilyBean.DataBean) object;
            DailyItem item3 = new DailyItem(find3List);
            items.add(item3);
        } else if (status == 4) {
            List<Find4Bean.DataBean> bean = (List<Find4Bean.DataBean>) object;
            YlItem item4 = new YlItem(bean.get(0));
            items.add(item4);
        } else if (status == 5) {
            Find5Bean.DataBean find5 = (Find5Bean.DataBean) object;
            find5List = find5.getRecords().get(0);
            RankItem item5 = new RankItem(find5List);
            items.add(item5);
        } else if (status == 6) {
            MessageBean1.DataBean beam = (MessageBean1.DataBean) object;
            List<MessageBean1.DataBean.RecordsBean> list = beam.getRecords();
            ZZSItem item6 = new ZZSItem(list);
            items.add(item6);
        } else if (status == 7) {
            ClassListBean.DataBean z7 = (ClassListBean.DataBean) object;
            List<ClassListBean.DataBean.RecordsBean> z7s = z7.getRecords();
            ClassSItem item8 = new ClassSItem(z7s);
            items.add(item8);
        }
        adapter.setItems(items);
        adapter.notifyDataSetChanged();
        findDailydapter.setRecyclerItemClickListener(new OnFindClickListener() {
            @Override
            public void onItemClick(long id, TextView textView, int position) {
                Log.d("wdawda", String.valueOf(position));
                if (position == 0) {
                    mPresenter.getDCX(getActivity(), Authorization, 1, id, Long.parseLong(userId), 7, textView);
                } else if (position == 1) {
                    mPresenter.getDCX(getActivity(), Authorization, 2, id, Long.parseLong(userId), 8, textView);
                } else if (position == 2) {
                    mPresenter.getDCX(getActivity(), Authorization, 3, id, Long.parseLong(userId), 9, textView);
                }
            }
        });


    }

    private void initRecyclerView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        findRecyclerview.setLayoutManager(layoutManager);
        adapter = new MultiTypeAdapter();
        adapter.register(HDItem.class, new FindHDAdapter());
        adapter.register(Find2Tiem.class, new FindHTAdapter());
        adapter.register(DailyItem.class, findDailydapter);
        adapter.register(YlItem.class, new FindYLAdapter());
        adapter.register(RankItem.class, new FindRankdapter());
        adapter.register(ZZSItem.class, zzAdapter);
        adapter.register(ClassSItem.class, new ClassSAdapter());
        findRecyclerview.setAdapter(adapter);
        items = new Items();
        findDailydapter.setRecyclerItemClickListener(new OnFindClickListener() {
            @Override
            public void onItemClick(long id, TextView textView, int position) {
                if (position == 0) {
                    mPresenter.getDCX(getActivity(), Authorization, 1, id, Long.parseLong(userId), 7, textView);
                } else if (position == 1) {
                    mPresenter.getDCX(getActivity(), Authorization, 2, id, Long.parseLong(userId), 8, textView);
                } else if (position == 2) {
                    mPresenter.getDCX(getActivity(), Authorization, 3, id, Long.parseLong(userId), 9, textView);
                }
            }
        });

    }


    @Override
    public void onError(Throwable throwable) {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder1.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder1 = ButterKnife.bind(this, rootView);
        return rootView;
    }
}
